package cn.kduck.code.entity.query;

import cn.kduck.core.dao.definition.BeanDefDepository;
import cn.kduck.core.dao.definition.BeanEntityDef;
import cn.kduck.core.dao.query.QueryCreator;
import cn.kduck.core.dao.query.QuerySupport;
import cn.kduck.core.dao.sqlbuilder.ConditionBuilder.ConditionType;
import cn.kduck.core.dao.sqlbuilder.SelectBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;

import static cn.kduck.code.Constants.GLOBAL_CONSTANT_YES;
import static cn.kduck.code.entity.service.EntityService.CODE_ENTITY_FIELD;

@Component
public class EntityFieldQuery implements QueryCreator {

    @Override
    public QuerySupport createQuery(Map<String, Object> paramMap, BeanDefDepository depository) {
        BeanEntityDef entityDef = depository.getEntityDef(CODE_ENTITY_FIELD);
        SelectBuilder selectBuilder = new SelectBuilder(entityDef, paramMap);
        selectBuilder.where()
                .and("ENTITY_ID", ConditionType.EQUALS,"entityId",true)
                .and("IS_KEY", ConditionType.EQUALS,"isKey")
                .and("FIELD_CODE", ConditionType.EQUALS,"fieldCode")
                .and("IS_NAME_FIELD", ConditionType.EQUALS,"isNameField")
                .and("CAN_VISIBLE",ConditionType.EQUALS,"canVisible")
                .orderBy().asc("ORDER_NUM");
        if(paramMap.containsKey("fieldNameOrCode")){
            selectBuilder.get().groupBegin("FIELD_NAME",ConditionType.CONTAINS,"fieldNameOrCode").or("FIELD_CODE",ConditionType.CONTAINS,"fieldNameOrCode").groupEnd();
        }
        if(paramMap.containsKey("isDictField") && ((Integer)paramMap.get("isDictField")).intValue() == GLOBAL_CONSTANT_YES){
            selectBuilder.get().and("DICT_CATEGORY_CODE",ConditionType.IS_NOT_BLANK);
        }
        return selectBuilder.build();
    }
}
